package com.bl.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fanhaotian
 */
@Component
public class JwtUtil {

     /**
      * 创建token
      *
      * @param s
      * @return
      * @throws UnsupportedEncodingException
      */
     public String SignToken(String s) throws UnsupportedEncodingException {
          //1.设置签名算法
          Algorithm algorithm = Algorithm.HMAC256("secret");
          //2.设置头部信息
          Map header = new HashMap();
          header.put("typ", "JWT");
          header.put("alg", "HS256");
          //3.创建token
          String token = JWT.create()
                            //1.设置头部
                            .withHeader(header)
                            //2.设置载荷
                            .withIssuer("auth0")
                            .withIssuedAt(new Date())
                            .withClaim("user", s)
                            //3.设置签名
                            .sign(algorithm);
          return token;
     }

     //解析token
     public String VerifyToekn(String token) {
          Algorithm algorithm = null;
          try {
               algorithm = Algorithm.HMAC256("secret");
               JWTVerifier verifier = JWT.require(algorithm)
                                         .withIssuer("auth0")
                                         .build(); //Reusable verifier instance
               DecodedJWT jwt = null;
               try {
                    jwt = verifier.verify(token);
               } catch (IllegalArgumentException e) {
                    System.out.println("非法参数异常");
                    return null;
               }
               //从jwt中获取到用户的信息
               String user = jwt.getClaim("user").asString();
               return user;
          } catch (JWTDecodeException e) {
               System.out.println("JWT解码异常");
          }
          return null;
     }

}
